package com.xframe.xdal.core.util.redis.command;


import com.xframe.xdal.core.util.redis.pool.IRedisPool;
import redis.clients.jedis.commands.BasicCommands;

import java.util.HashMap;
import java.util.Map;

public class RedisCommand {
    IRedisPool redisPool;

    private Map<String, Object> commands;

    public RedisCommand(IRedisPool redisPool){
        this.redisPool = redisPool;
        commands = new HashMap<>();
        commands.put(RedisCommandEnum.KEY.toString(), new KeyCommand(this.redisPool));
        commands.put(RedisCommandEnum.SET.toString(), new SetCommand(this.redisPool));
        commands.put(RedisCommandEnum.HASH.toString(), new HashCommand(this.redisPool));
        commands.put(RedisCommandEnum.GET.toString(), new GetCommand(this.redisPool));
        commands.put(RedisCommandEnum.LIST.toString(), new ListCommand(this.redisPool));
        commands.put(RedisCommandEnum.GATHER.toString(), new GatherCommand(this.redisPool));
    }

    public <T> T getClient(){
        return (T) redisPool.getResource();
    }

    public <T> void close(T client){
        redisPool.close(client);
    }

    public ListCommand getListCmd(){
        return getCmd(RedisCommandEnum.LIST);
    }
    public KeyCommand getKeyCmd(){
        return getCmd(RedisCommandEnum.KEY);
    }
    public SetCommand getSetCmd(){
        return getCmd(RedisCommandEnum.SET);
    }
    public HashCommand getHashCmd(){
        return getCmd(RedisCommandEnum.HASH);
    }

    public GetCommand getGetCmd(){
        return getCmd(RedisCommandEnum.GET);
    }

    public GatherCommand getGatherCommand(){
        return getCmd(RedisCommandEnum.GATHER);
    }

    public <T> T getCmd(RedisCommandEnum redisCommandEnum){
        return (T)commands.get(redisCommandEnum.toString());
    }
    /**
     * 以秒为单位，返回给定 key 的剩余生存时间(TTL, time to live)。
     *
     * @param index   key
     *
     * @return 当 key 不存在时，返回 -2 。 当 key 存在但没有设置剩余生存时间时，返回 -1 。否则，以秒为单位，返回 key 的剩余生存时间。
     */
    public String select(int index) {
        BasicCommands jedis = this.redisPool.getBasicCommands();
        try {
            if(jedis != null) {
                return jedis.select(index);
            }
            return "The operation is not supported";
        } finally {
            this.redisPool.close(jedis);
        }
    }

    public String ping() {
        BasicCommands jedis = this.redisPool.getBasicCommands();
        try {
            if(jedis != null) {
                return jedis.ping();
            }
            return "The operation is not supported";
        } finally {
            this.redisPool.close(jedis);
        }
    }

}
